<template>
  <div class="scatter-plot">
    <div ref="chart_ref"></div>
    <t-form class="config-form">
      <t-form-item label="Vega 工具栏">
        <t-switch size="large" v-model="chart_config.use_action_btn"></t-switch>
      </t-form-item>
    </t-form>
  </div>
</template>

<script setup lang="ts">
import vegaEmbed, { VisualizationSpec } from 'vega-embed'
import { onMounted, reactive, ref, toRaw, watchEffect } from 'vue'

const chart_ref = ref()

const chart_config = reactive({
  use_action_btn: false,
  spec: <VisualizationSpec>{
    width: 500,
    height: 500,
    params: [
      {
        name: 'grid',
        select: 'interval',
        bind: 'scales',
      },
      {
        name: 'size',
        value: 100,
        bind: { input: 'range', min: 20, max: 500, step: 1 },
      },
    ],
    data: {
      values: [
        { a: 'A', b: 28 },
        { a: 'B', b: 55 },
        { a: 'C', b: 43 },
        { a: 'D', b: 91 },
        { a: 'E', b: 81 },
        { a: 'F', b: 53 },
        { a: 'G', b: 19 },
        { a: 'H', b: 87 },
        { a: 'I', b: 52 },
      ],
    },
    mark: {
      type: 'circle',
      size: { expr: 'size' },
      color: '#2e66bf',
    },
    encoding: {
      x: {
        field: 'a',
        type: 'ordinal',
      },
      y: {
        field: 'b',
        type: 'quantitative',
      },
      tooltip: [{ field: 'a', type: 'ordinal', title: 'Category' }],
    },
  },
})

const refresh_chart = () => {
  console.log('Refresh chart')
  let spec = toRaw(chart_config.spec)
  vegaEmbed(chart_ref.value, spec, {
    renderer: 'svg',
    actions: chart_config.use_action_btn,
  }).then((res) => {
    console.log(res)
  })
}

watchEffect(() => {
  if (chart_ref.value) {
    refresh_chart()
  }
})
</script>

<style scoped>
.scatter-plot {
  display: flex;
  flex-direction: row;
}

.config-form {
  margin-left: 2rem;
  width: 20rem;
}
</style>
